"""
    qgram - a program to browse and analyze earthquake data 
    using spectrograms 
    Copyright (C) 2011 John Ivey

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Contact the authors through the Google Code website http://code.google.com/p/qgram
"""

import urllib2
import re
import time
import calendar

host =  "http://neic.usgs.gov/cgi-bin/tt/customize_finger.cgi"
request = "latitude=42.52&longitude=-83.36&response=&maxdist=180.&minmag=5&min1hz=0.0&min20s=0.0&finger_source=NEIC_DURING_PAST_MONTH&phases=ALL"

def getquakerecord(f):

    try:
        line=f.readline()
        linesplit = line.split()
        
        datestr = linesplit[0]+" "+linesplit[1]
        quaketime = time.strptime(datestr, "%Y/%m/%d %H:%M:%S")

        temp = re.search(r"(\d{1,3})([NSns])",linesplit[2]).groups()
        quakelat = int(temp[0])
        if temp[1].lower() == "s":
            quakelat = -1.0*quakelat
            
        temp = re.search(r"(\d{1,3})([EWew])",linesplit[3]).groups()
        quakelon = int(temp[0])
        if temp[1].lower() == "w":
            quakelat = -1.0*quakelon
            
        quakedepth = float(linesplit[4])
        
        quakemag = float(linesplit[5])
        comment = ""
        if len(linesplit) > 5:
            for word in linesplit[6:]:
                comment = comment +" "+word
        
        quakerec = {"time": quaketime, "lat": quakelat, "lon":quakelon, "dep":quakedepth, "mag":quakemag, "comment":comment}
        phases = []
        
        # find start of arrival times section
        while not "#  code      time(s)  dy hr mn sec" in line:
            line = f.readline()
            
        # skip header line    
        line = f.readline()
        
        # Read arrival times until the header of the next quake is found
        while not "DATE-(UTC)-TIME" in line:
            linesplit = line.split()
            phasenum = float(linesplit[0])
            phase = linesplit[1]
            traveltime = float(linesplit[2])
            
            #arrtime = time.strtptime(linesp) 
            arrday = int(linesplit[3])
            arrhr = int(linesplit[4])
            arrmin = int(linesplit[5])
            arrsec = int(linesplit[6])
            # Construct arrival time string using date of quake plus arrival times from phase table
            # This does not take into account the "day" field of the phase arrival time
            arrtimestr = str(quaketime.tm_year)+"/"+str(quaketime.tm_mon)+"/"+str(quaketime.tm_mday)+" "+str(arrhr)+":"+str(arrmin)+":"+str(arrsec)
            # Convert to struct_time
            arrtime = time.strptime(arrtimestr, "%Y/%m/%d %H:%M:%S")
            # Convert to seconds from epoch
            arrtimesec = calendar.timegm(arrtime)
            # Add one day to date if the arrival time is on the next day
            arrtimesec = arrtimesec + 3600*24*arrday
            # convert back to struct_time
            arrtime = time.gmtime(arrtimesec)

            phaserec = {"num":phasenum, "phase":phase, "traveltime":traveltime, "arrtime":arrtime}
            phases.append(phaserec)
            line = f.readline()
        quakerec["phases"] = phases
        return quakerec
    except:
        return None
    
def getquakes():
    conn = urllib2.Request(host, request)
    f = urllib2.urlopen(conn)
    
    line = f.readline()
    quakes=[]
    while not "DATE-(UTC)-TIME" in line:
        line = f.readline()
    quake = getquakerecord(f)
    while quake:
        for phase in quake["phases"]:
            if phase["phase"] == "LQ":
                pass
        quakes.append(quake)
        quake = getquakerecord(f)
    return quakes
 
#print getquakes()
